package com.platform.api;

import com.platform.annotation.IgnoreAuth;
import com.platform.cache.J2CacheUtils;
import com.platform.entity.SmsLogVo;
import com.platform.entity.UserVo;
import com.platform.service.ApiUserService;
import com.platform.utils.R;
import com.platform.validator.Assert;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 注册
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2017-03-26 17:27
 */
@Api(tags = "注册")
@RestController
@RequestMapping("/api/register")
public class ApiRegisterController{
    @Autowired
    private ApiUserService userService;

    /**
     * 注册
     */
    @ApiOperation(value = "注册")
    @IgnoreAuth
    @RequestMapping("register")
    public R register(String mobile, String password,String Code) {
        Assert.isBlank(mobile, "手机号不能为空");
        Assert.isBlank(password, "密码不能为空");
        Assert.isBlank(Code, "验证码不能为空");
        List<UserVo> users = userService.queryByMobile(mobile);
        if(users != null && users.size()>0){
            return R.error("手机号码已被注册");
        }
        SmsLogVo smsLogVo = (SmsLogVo)J2CacheUtils.get("code" + mobile);
        if(smsLogVo == null || !smsLogVo.getSms_code().equals(Code)){
            return R.error("验证码有误");
        }
        userService.save(mobile, password);
        J2CacheUtils.remove("code"+mobile);
        return R.ok("注册成功");
    }

    /**
     * 找回密码
     */
    @ApiOperation(value = "找回密码")
    @IgnoreAuth
    @RequestMapping("findPassword")
    public R findPassword(String mobile, String password,String Code) {
        Assert.isBlank(mobile, "手机号不能为空");
        Assert.isBlank(password, "新密码不能为空");
        Assert.isBlank(Code, "验证码不能为空");
        List<UserVo> users = userService.queryByMobile(mobile);
        if(users != null){
            if(users.size()==0){
                return R.error("账户不存在");
            }else if(users.size()>1){
                return R.error("账户异常");
            }
        }else{
            return R.error("账户不存在");
        }
        SmsLogVo smsLogVo = (SmsLogVo)J2CacheUtils.get("code" + mobile);
        if(smsLogVo == null || !smsLogVo.getSms_code().equals(Code)){
            return R.error("验证码有误");
        }
        users.get(0).setPassword(DigestUtils.sha256Hex(password));
        userService.update(users.get(0));
        J2CacheUtils.remove("code"+mobile);
        return R.ok("密码修改成功");
    }
}
